package com.turing.usdtpay.mvp.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.turing.usdtpay.R;
import com.turing.usdtpay.adapter.OrderAdapter;
import com.turing.usdtpay.base.BaseFragment;
import com.turing.usdtpay.entity.OrderAllData;
import com.turing.usdtpay.entity.OrderData;
import com.turing.usdtpay.entity.OrderInfoData;
import com.turing.usdtpay.entity.OrderListData;
import com.turing.usdtpay.entity.OrderManagerData;
import com.turing.usdtpay.mvp.activity.BuyOrderActivity;
import com.turing.usdtpay.mvp.activity.OrderPayActivity;
import com.turing.usdtpay.mvp.activity.OrderReceiptActivity;
import com.turing.usdtpay.mvp.activity.SellOrderActivity;
import com.turing.usdtpay.mvp.contract.OrderManagerContract;
import com.turing.usdtpay.mvp.dialog.CancelOrderDialog;
import com.turing.usdtpay.mvp.presenter.OrderManagerPresenter;
import com.turing.usdtpay.utils.DateUtils;
import com.turing.usdtpay.utils.FormatUtils;
import com.turing.usdtpay.utils.LogUtils;
import com.turing.usdtpay.utils.ToastUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @作者：JAY
 * @创建时间：2019/10/12 17:29
 * @描述：
 **/
public class OrderListFragment extends BaseFragment implements OrderManagerContract.View ,SwipeRefreshLayout.OnRefreshListener{
    private String TAG = "OrderListFragment";
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private RecyclerView mRecyclerView;
    private List<OrderData> mOrderDataList = new ArrayList<>();
    public static int TYPE_GOING = 1;
    public static int TYPE_COMPLETE = 2;
    public static int TYPE_CANCEL = 3;
    private FreshListener mFreshListener;
    private OrderManagerContract.Present mPresent;
    private int mCurrentPage = 1;
    private int mPage = 1;
    private int lastVisibleItem;
    private boolean hasMore = false;
    private OrderAdapter mAdapter;
    private double mRate;
    private boolean isLoading = false,isUIVisible = false;
    public static OrderListFragment newInstance(Bundle bundle) {
        OrderListFragment fragment = new OrderListFragment();
        if (bundle != null) {
            fragment.setArguments(bundle);
        }
        return fragment;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        LogUtils.d(TAG,hashCode()+"fragment,setUserVisibleHint :"+isVisibleToUser);
    }

    private void lazyLoad() {
        //这里进行双重标记判断,是因为setUserVisibleHint会多次回调,并且会在onCreateView执行前回调,必须确保onCreateView加载完毕且页面可见,才加载数据
        if (!isLoading && isUIVisible) {
            if (mPresent != null){
                mPresent.getOrderList(getActivity(),mCurrentPage,1,10,true);
                //数据加载完毕,恢复标记,防止重复加载
                isLoading = true;
                isUIVisible = false;
            }
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LogUtils.d(TAG,hashCode()+"fragment,onCreate");
        if (mPresent == null){
            setPresenter(new OrderManagerPresenter(this));
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_order_going, null);
        initView(view);
        initData();
        initRecycler();
        return view;
    }

    private void initView(View view) {
        mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_layout);
        mSwipeRefreshLayout.setColorSchemeResources(R.color.colorBlue);
        mSwipeRefreshLayout.setOnRefreshListener(this);
    }

    private void initData() {
        mOrderDataList.clear();
        Bundle bundle = getArguments();
        if (bundle != null){
            int type = bundle.getInt("type");
            LogUtils.d(TAG,hashCode()+"fragment,onCreateView : type ="+type);
            mCurrentPage = type;
//            if (isUIVisible){
//                mPresent.getOrderList(getActivity(),mCurrentPage,mPage,10,true);
//            }
            mPresent.getOrderList(getActivity(),mCurrentPage,mPage,10,true);
        }else {
            LogUtils.d(hashCode()+TAG+" bundle = null");
        }
    }

    private void setData(int type,List<OrderListData> list){
        for (int i = 0;i<list.size();i++){
            OrderListData listData = list.get(i);
            OrderData data = new OrderData();
            data.setOrderType(listData.getType());
            data.setPrice(mRate+" CNY/USDT");
            data.setCount(FormatUtils.NoumberFromat8(((double)listData.getMoney()/100)/mRate));
            data.setTotal(FormatUtils.NoumberFromat2((double)listData.getMoney()/100)+" CNY");
            data.setTime(DateUtils.dateToStrLong(new Date(listData.getAdd_time()*1000L)));
            data.setLimit(DateUtils.dateToStrLong(new Date(listData.getOver_time()*1000L)));
            data.setState(listData.getStatus());
            data.setPayType(listData.getPay_type());
            data.setOrderId(listData.getOrder());
            Date now = new Date(System.currentTimeMillis()/1000);
            Date limit = new Date(listData.getOver_time());
            double second = DateUtils.getDistanceTimeSecond(now, limit);
            if (second == 0){
                data.setTimeOut(true);
            }else {
                data.setTimeOut(false);
            }
            mOrderDataList.add(data);
        }
    }

    private void initRecycler() {
        final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(layoutManager);
        mAdapter = new OrderAdapter(getActivity(), mOrderDataList);
        mAdapter.setOnClickListener(new OrderAdapter.OnClickListener() {
            @Override
            public void onPay(String order) {
                mPresent.getBuyOrder(getActivity(),order,1);
            }

            @Override
            public void onComplete(String order) {
                mPresent.getBuyOrder(getActivity(),order,2);
            }

            @Override
            public void onCancel(final String order) {
                CancelOrderDialog dialog = new CancelOrderDialog(getActivity());
                dialog.setOnClickListener(new CancelOrderDialog.OnClickListener() {
                    @Override
                    public void onCancel() {
                        mPresent.cancelOrder(getActivity(), order);
                    }
                });
                dialog.show();
            }

            @Override
            public void onInfo(int type,String order) {
                if (type == 1){
                    mPresent.getBuyOrder(getActivity(),order,3);
                }else {
                    mPresent.getBuyOrder(getActivity(),order,4);
                }

            }
        });
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE){
                    if (lastVisibleItem +1 == mAdapter.getItemCount()){
                        if (hasMore){
                            mPage = ++mPage;
                            mPresent.getOrderList(getActivity(),mCurrentPage,mPage,10,false);
                        }else {
                            ToastUtils.showNormolToast(getActivity(),"已经没有更多了");
                        }
                    }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
            }
        });
    }


    @Override
    public void onSuccess(OrderManagerData data, int type, boolean fresh) {
        LogUtils.d(hashCode()+TAG+" data = "+data);
        mRate = (double) data.getMoney_change_usdt()/100;
        LogUtils.d(hashCode()+TAG+" type = "+type+",fresh = "+fresh);
        if (fresh){
            if (type == data.getStatus()){
                mOrderDataList.clear();
                mSwipeRefreshLayout.setRefreshing(false);
                mPage = 1;
                setData(data.getStatus(),data.getList_info());
                mAdapter.updateDate(mOrderDataList);
                LogUtils.d("mOrderDataList.size -->"+mOrderDataList.size());
            }
        }else {
            if (type == data.getStatus()){
                setData(data.getStatus(),data.getList_info());
                mAdapter.updateDate(mOrderDataList);
                if (data.getList_info().size() >0){
                    hasMore = true;
                }else {
                    hasMore = false;
                }
            }

        }
    }

    @Override
    public void cancelSuccess() {
        ToastUtils.showNormolToast(getActivity(),"订单已取消");
        mPresent.getOrderList(getActivity(),mCurrentPage,1,10,true);
        updateOrder();
    }

    @Override
    public void getSuccess() {
    }

    @Override
    public void paySuccess() {
    }

    @Override
    public void getOrderSuccess(OrderInfoData data ,int type) {
        if (type == 1){
            Intent intent = new Intent(getActivity(), BuyOrderActivity.class);
            intent.putExtra("data",data);
            startActivityForResult(intent,1000);
        }else if (type == 2){
            Intent intent = new Intent(getActivity(), SellOrderActivity.class);
            intent.putExtra("data",data);
            startActivityForResult(intent,2000);
        }else if (type == 3){
            Intent intent = new Intent(getActivity(), OrderPayActivity.class);
            intent.putExtra("data",data);
            startActivity(intent);
        }else if (type == 4){
            Intent intent = new Intent(getActivity(), OrderReceiptActivity.class);
            intent.putExtra("data",data);
            startActivity(intent);
        }
    }

    @Override
    public void onFail(String msg) {
        mSwipeRefreshLayout.setRefreshing(false);
        ToastUtils.showNormolToast(getActivity(),msg);
    }

    @Override
    public void setPresenter(OrderManagerContract.Present presenter) {
        mPresent = presenter;
    }

    @Override
    public void onRefresh() {
        if (mPresent != null){
            mPresent.getOrderList(getActivity(),mCurrentPage,1,10,true);
        }
    }

    public interface FreshListener{
        public void onFresh(int type,int num);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1000&&resultCode == 1){
            mPresent.getOrderList(getActivity(),mCurrentPage,1,10,true);
            updateOrder();
        }else if (requestCode == 2000&&resultCode == 2){
            mPresent.getOrderList(getActivity(),mCurrentPage,1,10,true);
            updateOrder();
        }
    }
}
